package com.robam.cloud.gatewayzuul.filter;

import com.robam.cloud.common.bean.common.Constant;
import com.robam.cloud.common.bean.restful.entity.RespMsg;
import com.robam.cloud.gatewayzuul.config.TokenAuthWhitelistConfig;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class TokenFilter extends ZuulFilter {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    TokenAuthWhitelistConfig tokenAuthWhitelistConfig;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();

        if (!ctx.sendZuulResponse()) {
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        for (String au : tokenAuthWhitelistConfig.getAuthWhite()
        ) {
            if (isMatch(request.getServletPath(), au)) {
                requestContext(context, true, RespMsg.RESULT_CODE_200, null);
                return null;
            }
        }
        String token = request.getHeader(Constant.TOKENNAME);

        if (token == null) {
            requestContext(context, false, RespMsg.RESULT_CODE_401, "unAuthrized");
            return null;
        } else {
            Object accountId = redisTemplate.opsForValue().get(Constant.TOKENNAME + ":" + token);
            if (accountId == null) {
                requestContext(context, false, RespMsg.RESULT_CODE_401, "unAuthrized");
            }
            return null;
        }


    }


    private void requestContext(RequestContext requestContext, boolean status, int code, String msg) {
        requestContext.setSendZuulResponse(status);
        requestContext.setResponseStatusCode(code);
        requestContext.setResponseBody(msg);
    }

    private boolean isMatch(String s, String p) {
        int i = 0;
        int j = 0;
        int starIndex = -1;
        int iIndex = -1;

        while (i < s.length()) {
            if (j < p.length() && (p.charAt(j) == '?' || p.charAt(j) == s.charAt(i))) {
                ++i;
                ++j;
            } else if (j < p.length() && p.charAt(j) == '*') {
                starIndex = j;
                iIndex = i;
                j++;//'*' can match 0 or above 0 characters
            } else if (starIndex != -1) {
                //such as "abggggb","*b"
                //so every time matching starts form the fisrt index of *
                //can avoid the case above
                j = starIndex + 1;
                i = iIndex + 1;
                iIndex++;
            } else {
                return false;
            }
        }

        while (j < p.length() && p.charAt(j) == '*') {
            ++j;
        }

        return j == p.length();
    }
}
